package com.example.demo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/session")
public class SessionController {
    @RequestMapping("/getCk")
    /*
    获取cookie方法一
    * */
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if(cookies != null){

            Arrays.stream(cookies).forEach(ck -> System.out.println(ck.getName()+": "+ck.getValue()));
        }
        return "获取cookie";
    }

    @RequestMapping("/getCk2")
    /*
    获取cookie方法二
    * */
    public String getCookie(@CookieValue("cookie") String cookie){

        return "获取cookie:  "+cookie;
    }

    //设置session
    @RequestMapping("/setSess")
    public String setSession(HttpServletRequest  request ){
        //从cookie中获取SessionId，根据sessionId获取session对象，如果没有获取到，会创建一个session对象
        HttpSession session = request.getSession();

        session.setAttribute("name","zhangsan");


        return "设置session成功";
    }
    /*
获取session方法一
* */
    @RequestMapping("/getSess")
    public String getSession(HttpServletRequest  request ){
        HttpSession session = request.getSession();
        String name =(String) session.getAttribute("name");
        return "从session获取name："+name;
    }
    /*
   获取session方法二
   HttpSession：封装获取sesionId方法
   * */
    @RequestMapping("/getSess2")
    public String getSession2(HttpSession session ){
        String name =(String) session.getAttribute("name");
        return "从session获取name："+name;
   }
   /*
   获取session方法三
   注解@SessionAttribute：把获取sessionId和session对象全部封装在一起了
   * */
    @RequestMapping("/getSess3")
    public String getSession3(@SessionAttribute String name){
        return "从session获取name："+name;
   }
   /*
   * 获取header信息
   * */
    @RequestMapping("/getheader")
   public  String getHeader(@RequestHeader("User-Agent") String UserAgent){
       return "从header中获取信息:"+UserAgent;
   }
}
